from flask import Blueprint, request, render_template, g, redirect, url_for
from .forms import QuestionForm,AnswerForm
from exts import db
from decorators import login_required
from flask import render_template
from models import QuestionModel,AnswerModel

# 创建对象:蓝图名称，和py文件名保持一致 + 固定写法，表示当前这个模块 + url前缀
bp = Blueprint("qa", __name__, url_prefix="/")

# 此处的前缀是根路径，将“首页”也涵盖进该模板里了

@bp.route("/")
def index():
    # 除了输出首页页面，还要输出存在的具体问答
    # 这里拿到“问题数据库”中的数据，并进行创建时间的倒序排序
    questions = QuestionModel.query.order_by(QuestionModel.create_time.desc()).all()
    # index首页中：{% for question in questions %}里面的questions就是上面的questions对象传给questions = questions中的前者
    return render_template("index.html", questions=questions)


@bp.route("/qa/detail/<qa_id>")
def qa_detail(qa_id):
    question = QuestionModel.query.get(qa_id)
    return render_template("detail.html", question=question)


# @bp.route("/answer/public",methods = ['POST'])
@bp.post("/answer/public")
@login_required
def public_answer():
        form = AnswerForm(request.form)
        if form.validate():
            content = form.content.data
            question_id = form.question_id.data
            # 前面进行了“是否登录”的拦截，登录就有g.user对象，就可以通过g.user.id传入author_id
            answer = AnswerModel(content = content,question_id = question_id,author_id = g.user.id)
            db.session.add(answer)
            db.session.commit()
            # 发布成功后，跳转回问题详情页面
            return redirect(url_for("qa.qa_detail",qa_id = question_id))
        else:
            print(form.errors)
            # 发布回答的格式错误，就回到问题详情页面，并返回问题id
            # 不能直接form.id，因为验证失败时当前表单的form可能为空，所以request.form拿用户提交的id
            return redirect(url_for("qa.qa_detail",qa_id = request.form.get("question_id")))

@bp.route("/qa/public", methods=['GET', 'POST'])
@login_required
def public_question():
    if request.method == 'GET':
        return render_template("public_question.html")
    else:
        form = QuestionForm(request.form)
        if form.validate():
            title = form.title.data
            content = form.content.data
            question = QuestionModel(title=title, content=content, author=g.user)
            db.session.add(question)
            db.session.commit()
            # TODO:跳转到详情页面
            return redirect("/")
        else:
            print(form.errors)
            return redirect(url_for("qa.public_question"))

@bp.route("/search")
def search():
    q = request.args.get("q")
    # 此处使用标题过滤，标题包含q的被搜索到
    questions = QuestionModel.query.order_by(QuestionModel.title.contains(q)).all()
    # questions = QuestionModel.query.filter(QuestionModel.content.contains(q)).all()
    return render_template("index.html",questions = questions)